import router from './router'
import store from './store'
import Cookies from 'js-cookie'
import nprogress from 'nprogress'
const TokenKey = 'zyr-Token'
const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  nprogress.start()
  if(Cookies.get(TokenKey)){
    console.log(111);   
    if(to.path=='/login'){
      next('/')
    }else{
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if(hasRoles){  
        console.log(router,'router2');       
        next()
      }else{      
        try{
          store.dispatch('getInfo').then(res=>{
            const accessRoutes = res
            console.log(accessRoutes,'accessRoutes111');  
            // 解决router.addRoutes不生效,页面不显示，无用
            // let routersList=router.options.routes 
            // router.options.routes =routersList.concat(accessRoutes)       
            router.addRoutes(accessRoutes)
            console.log(router,'router3');       
            next({ ...to, replace: true })
          })
          // 此处应该在获取roles后就执行路由添加
          // store.dispatch('user/getInfo').then(async res=>{
          //   let roles=["admin"]
          //   const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          //   router.addRoutes(accessRoutes)
          //   next({ ...to, replace: true })
          // })
        }catch (error) {
          store.dispatch('resetToken')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }

      }
    }
  }else{  
    if(whiteList.indexOf(to.path)!=-1){
    console.log(333);    
      next()
    }else{
      next('/login')
      nprogress.done()
    }
  }
})
router.afterEach((to, from) => {
  nprogress.done()
})